/*
 * TCPSocket.h
 *
 *  Created on: 21/06/2014
 *      Author: Vitor
 */

#ifndef TCPSOCKET_H_
#define TCPSOCKET_H_

#include <vector>
#include "SDL2/SDL_net.h"
#include <memory>
#include <stdlib.h>
#include <stdio.h>

class TCPSocket {
private:
	TCPsocket socket = nullptr;
	IPaddress ip_address;

public:
	TCPSocket();
	TCPSocket(const char* hostname, short port);
	TCPSocket(TCPsocket socket);
	virtual ~TCPSocket();

	bool accept(TCPSocket& incoming_connection);
	void open();
	void close();

	void send(const std::vector<char>& bytes);
	template<typename T> void send(T data) {
		if (SDLNet_TCP_Send(socket, &data, sizeof(T)) < sizeof(T)) {
			fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
			exit(1);
		}
	}

	bool recv(int size, std::vector<char>& storing_message);
	template<typename T> bool recv(T& storing_data) {
		if (SDLNet_TCP_Recv(socket, &storing_data, sizeof(T)) <= 0) {
			return false;
		}
		return true;
	}
};

#endif /* TCPSOCKET_H_ */
